<script setup>
import { reactive, ref } from 'vue'
import { Notification, Message } from 'element-ui'
import { uploadFile } from '@/api/uploadFile.js'
import { base64ToExcel } from '@/utils/index.js'
import ProDialog from '@/components/Dialog/index.vue'

// 最大文件上传数
const excelLimit = ref(1)
// dialog状态
const dialogVisible = ref(false)
// 父组件传过来的参数
const parameter = ref({})

const state = reactive({
  FilePath: '',
  FileName: '',
  result: {
    Fail: 0,
    Success: 0,
    FileId: '',
    FileName: '',
  },
})

// 接收父组件参数
const acceptParams = (params) => {
  parameter.value = params
  dialogVisible.value = true
}

// Excel 导入模板下载
const downloadTemp = () => {
  if (!parameter.value.tempUrl)
    return
  // 下载地址 替换成真实地址
  window.location.href = `${window.apiUrl}yytsljExcel/${parameter.value.tempUrl}`
}

/**
 * @description 图片上传
 * @param options 上传的文件
 * */
const uploadExcel = async (options) => {
  const excelFormData = new FormData()
  excelFormData.append('file', options.file)
  excelFormData.append('name', options.file.name)

  try {
    const data = await uploadFile(excelFormData)
    state.FilePath = data.FilePath
    state.FileName = data.FileName
  }
  catch (error) {
    options.onError(error)
  }
}

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file) => {
  const isExcel
		= file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const fileSize = file.size / 1024 / 1024 < 5
  if (!isExcel) {
    Notification({
      title: '温馨提示',
      message: '上传文件只能是 xls / xlsx 格式！',
      type: 'warning',
    })
  }
  if (!fileSize) {
    Notification({
      title: '温馨提示',
      message: '上传文件大小不能超过 5MB！',
      type: 'warning',
    })
  }
  return isExcel && fileSize
}

// 文件数超出提示
const handleExceed = () => {
  Notification({
    title: '温馨提示',
    message: '最多只能上传一个文件！',
    type: 'warning',
  })
}

// 上传错误提示
const excelUploadError = () => {
  Notification({
    title: '温馨提示',
    message: `上传${parameter.value.title}失败，请您重新上传！`,
    type: 'error',
  })
}

// 上传成功提示
const excelUploadSuccess = () => {
  Notification({
    title: '温馨提示',
    message: `上传${parameter.value.title}成功！`,
    type: 'success',
  })
}

const closeDialog = () => {
  dialogVisible.value = false
}

/** 下载错误提示excel */
const downloadErr = () => {
  parameter.value.downExcelApi({
    FileId: state.result.FileId,
    FileName: state.result.FileName,
  }).then((res) => {
    base64ToExcel(res.FileBase64, res.FileName)
  })
}

const handleConfirm = () => {
  if (state.FilePath && state.FileName) {
    parameter.value.importApi({
      FilePath: state.FilePath,
      FileName: state.FileName,
    }).then((res) => {
      if (res.Fail === 0) {
        dialogVisible.value = false
        Message.success('导入成功!')
        parameter.value.getTableList && parameter.value.getTableList()
      }
      else {
        state.result = res
        Notification({
          title: '温馨提示',
          message: `${res.Fail} 条数据导入失败!`,
          type: 'error',
        })
      }
    })
  }
  else {
    Message.warning('请上传文件!')
  }
}
defineExpose({
  acceptParams,
})
</script>

<template>
  <ProDialog
    :visible.sync="dialogVisible"
    :title="`${parameter.title}`"
    width="585px"
    @confirm="handleConfirm"
    @cancel="closeDialog"
  >
    <el-form class="drawer-multiColumn-form">
      <el-form-item label="模板下载 :">
        <el-button type="primary" icon="el-icon-download" @click="downloadTemp">
          点击下载
        </el-button>
      </el-form-item>
      <el-form-item label="文件上传 :">
        <el-upload
          action="string"
          class="upload"
          :drag="true"
          :limit="excelLimit"
          :show-file-list="true"
          :http-request="uploadExcel"
          :before-upload="beforeExcelUpload"
          :on-exceed="handleExceed"
          :on-success="excelUploadSuccess"
          :on-error="excelUploadError"
          accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传 .xls , .xlsx 标准格式文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <div v-if="state.result.Fail" class="result">
      <div>{{ state.result.FileName }}</div>
      <div>
        <div>
          <span>{{ state.result.Success }}</span>
          <span>/</span>
          <span>{{ state.result.Fail }}</span>
        </div>
        <div>
          <el-button v-throttle="downloadErr" type="primary" link size="small">
            下载
          </el-button>
        </div>
      </div>
    </div>
  </ProDialog>
</template>

<style lang="scss" scoped>
.upload {
  width: 80%;
}

.result {
  border: 1px solid #E6E6E6;
  border-radius: 3px;
  margin-bottom: 10px;
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;

  &>div:nth-child(2) {
    display: flex;
    justify-content: space-between;

    &>div:nth-child(1) {
      width: 100px;

      &>span:nth-child(1) {
        color: #339933;
      }
      &>span:nth-child(2) {
        margin: 0px 5px;
      }
      &>span:nth-child(3) {
        color: #CC3333;
      }
    }
  }
}
</style>
